package com.example.myapplication.socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpClient {
    private static UdpClient instance;
    private DatagramSocket socket;
    private InetAddress serverAddress;
    private int serverPort;

    private UdpClient() {
        try {
            socket = new DatagramSocket();
            serverAddress = InetAddress.getByName("10.0.2.2");
            serverPort = 8234;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static synchronized UdpClient getInstance() {
        if (instance == null) {
            instance = new UdpClient();
        }
        return instance;
    }

    public void sendMessage(String message) {
        try {
            byte[] buffer = message.getBytes("GBK");
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length, serverAddress, serverPort);
            socket.send(packet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String receiveMessage() {
        byte[] buffer = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
        try {
            socket.receive(packet);
            return new String(packet.getData(), 0, packet.getLength(),"GBK");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}